// @Title 上传文件
// @Description 请填写文件描述
// @Author 赵伟 2021/4/9 10:15

package v1

import (
    "authserver/global/response"
    "authserver/utils"
    "github.com/gin-gonic/gin"
	"io/ioutil"
	"strings"
)

// @Tags 文件管理
// @Summary 上传文件
// @Router /file/upload [post]
func UploadFile(c *gin.Context) {
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		response.FailWithMessage("上传文件失败", c)
	} else {
		// 文件上传后拿到文件路径
		err, filePath, fileKey := utils.Upload(header)
		if err != nil {
			response.FailWithMessage("上传文件失败", c)
		} else {
			data := make(map[string]string)
			data["imageUrl"] = filePath
			data["fileKey"] = fileKey
			response.OkWithData(data, c)
		}
	}
}

// @Tags 文件管理
// @Summary 上传文件——文件名没有附加key
// @Router /file/uploadNotKey [post]
func UploadFileNotKey(c *gin.Context) {
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		response.FailWithMessage("上传文件失败", c)
	} else {
		// 文件上传后拿到文件路径
		err, filePath, fileKey := utils.Upload(header)
		if err != nil {
			response.FailWithMessage("上传文件失败", c)
		} else {
			data := make(map[string]string)
			data["imageUrl"] = filePath
			data["fileKey"] = fileKey
			response.OkWithData(data, c)
		}
	}
}

// @Tags 文件管理
// @Summary 上传文件
// @Router /file/uploadTxt [post]
func UploadTextFile(c *gin.Context) {
	var (
		bs         []byte
		readString string
	)
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		response.FailWithMessage("上传文件失败", c)
		return
	}
	f, err := header.Open()
	bs, err = ioutil.ReadAll(f)
	if err != nil {
		response.FailWithMessage("文件解析失败", c)
		return
	}
	readString = string(bs)
	readString = strings.Replace(readString, " ", "", -1)
	readString = strings.Replace(readString, "，", ",", -1)
	readString = strings.ToUpper(readString)
	response.OkWithData(readString, c)
}

// @Tags 文件管理
// @Summary 上传文件
// @Router /file/getUploadToken [post]
func GetUploadToken(c *gin.Context) {
	upToken := utils.GetUploadToken()
	response.OkWithData(upToken, c)
}
